package example.com.nexd.collectionsdk.sdk.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;

import java.io.File;

/**
 * ExternalStorageHelper create by codingfish at 15/5/15
 * TODO:
 *
 * @Version V1.0
 */
public class ExternalStorageHelper {
    private ExternalStorageHelper() {
    }

    public static boolean isExternalStorageMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static File openMusicDirectory(Context context) {
        if (isExternalStorageMounted()) {
            return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ?
                    context.getExternalFilesDir(Environment.DIRECTORY_MUSIC) :
                    openDirectory("music");
        }
        return null;
    }

    private static File openDirectory(String dirname) {
        File f = null;
        if (isExternalStorageMounted()) {
            File storageDir = Environment.getExternalStorageDirectory();
            f = new File(storageDir, dirname);
            if (f != null && !f.exists()) {
                f.mkdirs();
            }
        }
        return f;
    }

    public static File openPublicPicturesDirectory() {
        if (isExternalStorageMounted()) {
            return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ?
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) :
                    openPublicDirectory("Pictures");
        }
        return null;
    }

    private static File openPublicDirectory(String dirname) {
        File f = null;
        if (isExternalStorageMounted()) {
            File storageDir = Environment.getExternalStorageDirectory();
            f = new File(storageDir, dirname);
            if (f != null && !f.exists()) {
                f.mkdirs();
            }
        }
        return f;
    }

    public static File getCacheDir(Context context) {
        return isExternalStorageMounted() ? getExternalCacheDir(context) : getCacheDirByContext(context);
    }

    private static File getExternalCacheDir(Context context) {
        return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ?
                context.getExternalCacheDir() :
                context.getCacheDir();
    }

    private static File getCacheDirByContext(Context context) {
        return context.getCacheDir();
    }
}
